import React, { useState, useEffect } from 'react'
import './index.less'
import { Swiper, Uploader, ActionSheet, Popup, Image } from 'react-vant'

// socket.io
import io from 'socket.io-client';
// socket
// import { socket } from '../../../../../utils/websocket'
// // jquery
import $ from "jquery"
import upload from '../../../../../utils/upload'
import {withRouter} from 'react-router-dom'
//功能面板
const panelList = [
    { title: "拍摄", icon: "#icon-paishexuanzhong" },
    { title: "视频通话", icon: "#icon-shipin" },
    { title: "位置", icon: "#icon-weizhi" },
    { title: "红包", icon: "#icon-hongbao" },
    { title: "转账", icon: "#icon-zhuanzhang" },
    { title: "语音输入", icon: "#icon-31yuyinxuanzhong" },
    { title: "收藏", icon: "#icon-shoucanghezi" },
]
const panelList1 = [
    { title: "个人名片", icon: "#icon-gerenxinxi" },
    { title: "文件", icon: "#icon-wenjian" },
    { title: "卡卷", icon: "#icon-kabao1" },
]
//底部功能面板
const Functionpanel = (props) => {
    /**
     * showPopup：是否展示功能面板块
     * setIsShowShot:是否打开（调用）摄像头
     */
    let { showPopup, setIsShowShot } = props;
    console.log(props);
    const afterRead = async (e) => {
        // let files = e.file;
        let files = e.target.files[0]
        upload(files, props)
        //异步方法（解决实时更新问题）
        setTimeout(() => {
            props.getMessageList()
        }, 100)
    };

    // 音视频状态框状态
    const actions = [{ name: '视频通话' }, { name: '语音通话' }];
    const [visible, setVisible] = useState(false);
    const onCancel = () => setVisible(false);
    // 音视频弹框状态
    const [visiblePopup, setVisiblePopup] = useState(false);

    // 麦克风状态
    const [ifOpen, setIfOpen] = useState(true)
    // 开关麦克风事件
    const OCmaikefeng = () => {
        let statusOpen = ifOpen
        setIfOpen(!statusOpen);
    }
    // 扬声器状态
    const [ifOpenloud, setIfOpenloud] = useState(true)
    // 开关扬声器事件
    const OCloudspeaker = () => {
        let statusOpen = ifOpenloud
        setIfOpenloud(!statusOpen);
    }
    // 挂断电话
    const dropped = () => {
        console.log(stream);
        if (stream) {
            stream.getTracks()[1].stop()
            stream.getTracks()[0].stop()
        }

        // 关闭弹框
        setVisiblePopup(false);
        console.log();
    }
    // 判断当前是视频通话还是语音通话
    const [ifVideoAndAudio, setIfVideoAndAudio] = useState()
    // 转成语音通话
    const switchVoice = () => {
        setIfVideoAndAudio(false)
    }


    const [stream, setStream] = useState()
    // 视频通话
    const videoCell = () => {
        //封装一部分函数
        function getUserMedia(constrains, success, error) {
            let promise;
            if (navigator.mediaDevices.getUserMedia) {
                //最新标准API
                promise = navigator.mediaDevices.getUserMedia(constrains).then(success).catch(error);
            } else if (navigator.webkitGetUserMedia) {
                //webkit内核浏览器
                promise = navigator.webkitGetUserMedia(constrains).then(success).catch(error);
            } else if (navigator.mozGetUserMedia) {
                //Firefox浏览器
                promise = navigator.mozGetUserMedia(constrains).then(success).catch(error);
            } else if (navigator.getUserMedia) {
                //旧版API
                promise = navigator.getUserMedia(constrains).then(success).catch(error);
            }
        }

        function canGetUserMediaUse() {
            return !!(navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
        }
        const localVideoElm = document.getElementById("video-local");
        const iceServer = {
            iceServers: [{ urls: ["stun:ss-turn1.xirsys.com"] }, { username: "CEqIDkX5f51sbm7-pXxJVXePoMk_WB7w2J5eu0Bd00YpiONHlLHrwSb7hRMDDrqGAAAAAF_OT9V0dWR1d2Vi", credential: "446118be-38a4-11eb-9ece-0242ac140004", urls: ["turn:ss-turn1.xirsys.com:80?transport=udp", "turn:ss-turn1.xirsys.com:3478?transport=udp"] }]
        };
        //PeerConnection
        var pc = [];
        var localStream = null;
        function InitCamera() {

            if (canGetUserMediaUse()) {
                getUserMedia({
                    video: true,
                    audio: true
                }, (stream) => {
                    localStream = stream;
                    setStream(localStream)
                    localVideoElm.srcObject = stream;
                }, (err) => {
                    console.log('访问用户媒体失败: ', err.name, err.message);
                });
            } else {
                alert('您的浏览器不兼容');
            }
        }
        function StartCall(parterName, createOffer) {

            pc[parterName] = new RTCPeerConnection(iceServer);

            //如果已经有本地流，那么直接获取Tracks并调用addTrack添加到RTC对象中。
            if (localStream) {

                localStream.getTracks().forEach((track) => {
                    pc[parterName].addTrack(track, localStream);//should trigger negotiationneeded event
                });

            } else {
                //否则需要重新启动摄像头并获取
                if (canGetUserMediaUse()) {
                    getUserMedia({
                        video: true,
                        audio: true
                    }, function (stream) {
                        localStream = stream;

                        localVideoElm.srcObject = stream;

                    }, function (error) {
                        console.log("访问用户媒体设备失败：", error.name, error.message);
                    })
                } else { alert('您的浏览器不兼容'); }

            }

            //如果是呼叫方,那么需要createOffer请求
            if (createOffer) {
                //每当WebRTC基础结构需要你重新启动会话协商过程时，都会调用此函数。它的工作是创建和发送一个请求，给被叫方，要求它与我们联系。
                pc[parterName].onnegotiationneeded = () => {
                    //https://developer.mozilla.org/zh-CN/docs/Web/API/RTCPeerConnection/createOffer

                    pc[parterName].createOffer().then((offer) => {
                        return pc[parterName].setLocalDescription(offer);
                    }).then(() => {
                        //把发起者的描述信息通过Signal Server发送到接收者
                        socket.emit('sdp', {
                            type: 'video-offer',
                            description: pc[parterName].localDescription,
                            to: parterName,
                            sender: socket.id
                        });
                    })
                };
            }

            //当需要你通过信令服务器将一个ICE候选发送给另一个对等端时，本地ICE层将会调用你的 icecandidate 事件处理程序。有关更多信息，请参阅Sending ICE candidates 以查看此示例的代码。
            pc[parterName].onicecandidate = ({ candidate }) => {
                socket.emit('ice candidates', {
                    candidate: candidate,
                    to: parterName,
                    sender: socket.id
                });
            };

            //当向连接中添加磁道时，track 事件的此处理程序由本地WebRTC层调用。例如，可以将传入媒体连接到元素以显示它。详见 Receiving new streams 。
            pc[parterName].ontrack = (ev) => {
                let str = ev.streams[0];

                if (document.getElementById(`${parterName}-video`)) {
                    document.getElementById(`${parterName}-video`).srcObject = str;
                } else {
                    let newVideo = document.createElement('video');
                    newVideo.id = `${parterName}-video`;
                    newVideo.autoplay = true;
                    newVideo.srcObject = str;
                    newVideo.style = { width: "200px", height: "200px", objectFit: "cover" }

                    document.getElementById('videos').appendChild(newVideo);
                }
            }
        }
        // let local = JSON.parse(localStorage.getItem('token'))
        const wsuri = 'ws://localhost:3000';//ws地址
        // 连接服务器, 得到与服务器的连接对象
        const socket = io(wsuri)
        // setSocket(socket)
        socket.on('connect', () => {
            InitCamera();

            //输出内容 其中 socket.id 是当前socket连接的唯一ID
            console.log('connect ' + socket.id);

            $('#user-id').text(socket.id);

            pc.push(socket.id);

            socket.emit('new user greet', {
                sender: socket.id,
                msg: 'hello world'
            });

            socket.on('need connect', (data) => {

                console.log(data);
                //创建新的li并添加到用户列表中
                let li = $('<li></li>').text(data.sender).attr('user-id', data.sender);
                $('#user-list').append(li);
                //同时创建一个按钮
                let button = $('<button class="call">通话</button>');
                button.appendTo(li);
                //监听按钮的点击事件, 这是个demo 需要添加很多东西，比如不能重复拨打已经连接的用户
                $(button).click(function () {
                    //$(this).parent().attr('user-id')
                    console.log($(this).parent().attr('user-id'));
                    //点击时，开启对该用户的通话
                    StartCall($(this).parent().attr('user-id'), true);
                });

                socket.emit('ok we connect', { receiver: data.sender, sender: socket.id });
            });
            //某个用户失去连接时，我们需要获取到这个信息
            socket.on('user disconnected', (socket_id) => {
                console.log('disconnect : ' + socket_id);

                $('#user-list li[user-id="' + socket_id + '"]').remove();
            })
            //链接吧..
            socket.on('ok we connect', (data) => {
                console.log(data);

                $('#user-list').append($('<li></li>').text(data.sender).attr('user-id', data.sender));
                //这里少了程序，比如之前的按钮啊，按钮的点击监听都没有。
            });

            //监听发送的sdp事件
            socket.on('sdp', (data) => {
                //如果时offer类型的sdp
                if (data.description.type === 'offer') {
                    //那么被呼叫者需要开启RTC的一套流程，同时不需要createOffer，所以第二个参数为false
                    StartCall(data.sender, false);
                    //把发送者(offer)的描述，存储在接收者的remoteDesc中。
                    let desc = new RTCSessionDescription(data.description);
                    //按1-13流程走的
                    pc[data.sender].setRemoteDescription(desc).then(() => {

                        pc[data.sender].createAnswer().then((answer) => {
                            return pc[data.sender].setLocalDescription(answer);
                        }).then(() => {
                            socket.emit('sdp', {
                                type: 'video-answer',
                                description: pc[data.sender].localDescription,
                                to: data.sender,
                                sender: socket.id
                            });

                        }).catch();//catch error function empty

                    })
                } else if (data.description.type === 'answer') {
                    //如果使应答类消息（那么接收到这个事件的是呼叫者）
                    let desc = new RTCSessionDescription(data.description);
                    pc[data.sender].setRemoteDescription(desc);
                }
            })

            //如果是ice candidates的协商信息
            socket.on('ice candidates', (data) => {
                console.log('ice candidate: ' + data.candidate);
                //{ candidate: candidate, to: partnerName, sender: socketID }
                //如果ice candidate非空（当candidate为空时，那么本次协商流程到此结束了）
                if (data.candidate) {
                    var candidate = new RTCIceCandidate(data.candidate);
                    //讲对方发来的协商信息保存
                    pc[data.sender].addIceCandidate(candidate).catch();//catch err function empty
                }
            })
        });
    }


    return (
        <div className={showPopup ? 'functionpanelBox slide' : 'functionpanelBox'}>
            <Swiper>
                <Swiper.Item>
                    <ul className="panelBox">
                        <li>
                            <input type="file" onChange={(e) => {
                                afterRead(e)
                            }} />
                            <p>
                                <svg fontSize={30} color="gray" className='icon' aria-hidden='true'>
                                    <use xlinkHref="#icon-zhaopian"></use>
                                </svg>
                            </p>
                            <p>照片</p>
                        </li>
                        {
                            panelList.map((item, index) => {
                                return <li onClick={(e) => {
                                    if (index === 0) {
                                        setIsShowShot(true)
                                    } else if (index === 1) {
                                        setVisible(true)
                                    }
                                    if (index === 2) {
                                        props.history.push('/main/map')
                                    }
                                }} key={index}>
                                    <p>
                                        <svg fontSize={30} color="gray" className='icon' aria-hidden='true'>
                                            <use xlinkHref={item.icon}></use>
                                        </svg>
                                    </p>
                                    <p>{item.title}</p>
                                </li>
                            })
                        }

                    </ul>
                </Swiper.Item>
                <Swiper.Item>
                    <ul style={{ width: "100%", height: "100%", display: "flex", flexWrap: "wrap", textAlign: "center", marginTop: "20px" }} className="panelBox">
                        {
                            panelList1.map((item, index) => {
                                return <li style={{ width: "25%", padding: "5px 0px" }} key={index}>
                                    <p style={{ width: "50px", height: "50px", background: "#fff", borderRadius: "10px", margin: "0 auto" }}>
                                        <svg fontSize={30} style={{ marginTop: "8px" }} color="gray" className='icon' aria-hidden='true'>
                                            <use xlinkHref={item.icon}></use>
                                        </svg>
                                    </p>
                                    <p>{item.title}</p>
                                </li>
                            })
                        }
                    </ul>
                </Swiper.Item>
            </Swiper>


            {/* 音视频通话下拉框 */}
            <ActionSheet
                visible={visible}
                onCancel={onCancel}
                actions={actions}
                cancelText="取消"
                onSelect={(action, index) => {
                    setVisiblePopup(true)
                    setVisible(false)
                    if (index === 0) {
                        setIfVideoAndAudio(true)
                        // 调用视频通话方法
                        videoCell()
                    } else if (index === 1) {
                        setIfVideoAndAudio(false)
                    }
                }}
            />
            {/* 音视频弹框 */}
            <Popup
                visible={visiblePopup}
                onClose={() => {
                    setVisiblePopup(false);
                }}
                style={{ width: "100%", height: "100%" }}
            >
                {
                    ifVideoAndAudio ? <div className='popupBox'>
                        <div className='popupBoxP'>
                            <video id="video-local" style={{ width: "100%", height: "100%", objectFit: 'cover' }} autoPlay={true}></video>
                            <div id="videos"></div>
                        </div>
                        <div className='cover'>
                            <ul id="user-list">

                            </ul>
                            <header style={{ padding: "5px 10px", display: "flex", alignItems: "center" }}>
                                <p style={{ padding: "5px", background: "rgba(0,0,0,.5)", borderRadius: "50%" }}>
                                    <svg className="icon" aria-hidden="true" style={{ color: "#fff", fontSize: "14px" }}>
                                        <use xlinkHref="#icon-xiaoping"></use>
                                    </svg>
                                </p>
                                <p style={{ margin: "0 auto" }}>拨号中</p>
                            </header>
                            <main>

                                <div className='headImg'>
                                    <Image width="100%" radius={5} src="/img/headImg.jpg" width="70px" height="18vw" />
                                    <div className="text">默认提示</div>
                                </div>
                                <div className='footer'>
                                    <ul>
                                        <li onClick={dropped}>
                                            <p style={{ background: "rgb(234,69,71)" }}>
                                                <svg className="icon" aria-hidden="true">
                                                    <use xlinkHref="#icon-14guaduan-2"></use>
                                                </svg>
                                            </p>
                                            <p>取消</p>
                                        </li>
                                        <li onClick={switchVoice}>
                                            <p style={{ background: "rgb(0,0,0,.4)" }}>
                                                <svg className="icon" aria-hidden="true" style={{ color: "#fff" }}>
                                                    <use xlinkHref="#icon-zhuanyuyin"></use>
                                                </svg>
                                            </p>
                                            <p>转成语音通话</p>
                                        </li>
                                    </ul>
                                </div>
                            </main>
                        </div>
                    </div> : <div className='popupBox'>
                        <p className="popupBoxP"></p>
                        <div className='cover'>
                            <header style={{ padding: "5px 10px", display: "flex", alignItems: "center" }}>
                                <p style={{ padding: "5px", background: "rgba(0,0,0,.5)", borderRadius: "50%" }}>
                                    <svg className="icon" aria-hidden="true" style={{ color: "#fff", fontSize: "14px" }}>
                                        <use xlinkHref="#icon-xiaoping"></use>
                                    </svg>
                                </p>
                                <p style={{ margin: "0 auto" }}>拨号中</p>
                            </header>
                            <main>
                                <div className='headImg'>
                                    <Image width="100%" radius={5} src="/img/headImg.jpg" width="70px" height="18vw" />
                                    <div className="text">默认提示</div>
                                </div>
                                <div className='footer'>
                                    <ul>
                                        <li onClick={OCmaikefeng}>
                                            <p style={!ifOpen ? { background: "rgb(49,49,49)" } : null}>
                                                <svg className="icon" aria-hidden="true" style={!ifOpen ? { color: "#fff" } : { color: "#000" }}>
                                                    <use xlinkHref={ifOpen ? "#icon-maikefeng1" : "#icon-bimai-01"}></use>
                                                </svg>
                                            </p>
                                            <p>{ifOpen ? '麦克风已开' : '麦克风已关'}</p>
                                        </li>
                                        <li onClick={dropped}>
                                            <p style={{ background: "rgb(234,69,71)" }}>
                                                <svg className="icon" aria-hidden="true">
                                                    <use xlinkHref="#icon-14guaduan-2"></use>
                                                </svg>
                                            </p>
                                            <p>取消</p>
                                        </li>
                                        <li onClick={OCloudspeaker}>
                                            <p style={ifOpenloud ? { background: "rgb(49,49,49)" } : { background: "#fff" }}>
                                                <svg className="icon" aria-hidden="true" style={ifOpenloud ? { color: "#fff" } : { color: "#000" }}>
                                                    <use xlinkHref={ifOpenloud ? "#icon-ai16" : "#icon-yangshengqi"}></use>
                                                </svg>
                                            </p>
                                            <p>{ifOpenloud ? '扬声器已关' : '扬声器已开'}</p>
                                        </li>
                                    </ul>
                                </div>
                            </main>
                        </div>
                    </div>
                }
            </Popup>
        </div>
    )
}
export default withRouter(Functionpanel)